import React, { PureComponent } from 'react';
import { connect } from 'dva';
import PateoTable from '@/components/common/PateoTable';
import PateoSearchForm from '@/components/common/PateoSearchForm';
import PateoAuthButtons from '@/components/common/PateoAuthButtons';
import styles from '@/components/common/PateoTable/TableList.less';
import { Card, Modal, Button, Space, Descriptions, Select } from 'antd';

const mapStateToProps = (state: any) => {
  return {
    listData: state.modelVehicleSeries.pageData,
    loading: state.loading.effects['modelVehicleSeries/postFetchPage'],
  };
};

const engineTypeData = [
  {
    value: 0,
    label: '燃油车FUEL'
  },
  {
    value: 1,
    label: '混动车HEV'
  },
  {
    value: 2,
    label: '电动车BEV'
  },
  {
    value: 3,
    label: '插电式混动PHEV',
  },
  {
    value: 4,
    label: '增程式混动REV',
  },
];
const bluetoothModuleTypeData = [
  {
    value: 1,
    label: '独立蓝牙元件',
  },
  {
    value: 2,
    label: 'Tbox蓝牙元件',
  }
];
const isAllInOneMachineDate = [
  {
    value: 1,
    label: '是',
  },
  {
    value: 0,
    label: '否',
  }
];

class index extends PureComponent {
  state = {
    isModalOpen: false,
    rightQuery: {},
    layerInfo: {},
    selectList: [],
    attribute: {},
    brandOptions: [],
    defaultBrand: '',
    selectBrand: ''
  };
  payloadUrl = '/msdevice/base/vehicle/type/page';
  payloadType = 'modelVehicleSeries/getFetchPage';
  searchRef = null;

  componentDidMount() {
    const { dispatch } = this.props;
    const query = this.props?.history?.location?.query;
    const {brandId} = query; 
    dispatch({
      type: 'basedata/brandFetch',
      callback: (res:any) => {
        if(JSON.stringify(query) == "{}"){
        this.setState({ 
           brandOptions: res?.data,
           defaultBrand: res?.data[0].brandCode,
           selectBrand: res?.data[0].brandCode
          });
          this.getList(query,res?.data[0].brandCode),
          // 车系查询
          this.getSeries(res?.data[0].brandCode);
        }else{//从车型车系跳转而来
          this.setState({ 
            brandOptions: res?.data,
            defaultBrand: brandId,
            selectBrand: brandId
           });
           this.getList(query,brandId),
           // 车系查询
           this.getSeries(brandId);
        }
        }
    });
    // 获取传参
    this.searchRef?.current?.setFieldsValue(query);
    this.setState(
      {
        rightQuery: { ...query },
      },

    );
  }
  //车系查询
  getSeries=(brandId:string)=>{
    const { dispatch } = this.props;
    dispatch({
      type: 'modelVehicleSeries/getData',
      payload: { url: '/msdevice/base/vehicle/series/bybrand/list', brandId },
      callback: res => {
        this.setState({
          selectList: res?.data,
        });
      },
    });
  }
  // 获取参数
  getList = (query:any, brandId:String) => {
    const { dispatch } = this.props;
    const { rightQuery } = this.state;
    const params = {
      ...query,
      brandId: brandId
    }
    dispatch({
      type: this.payloadType,
      payload: { url: this.payloadUrl, ...params },
    });
  };

  handleCancel = () => {
    this.setState({
      isModalOpen: false,
    });
  };
  getAttribute = () => {
    const { dispatch } = this.props;
    return new Promise(resolve => {
      dispatch({
        type: 'ability/getDataWithRes',
        payload: { url: '/msdevice/base/vehicle/msdevice/base/data/type/attribute/list' },
        callback: res => {
          const { data, statusCode } = res;

          if (statusCode === '0') {
            resolve(data);
          }
          resolve({ body_color: {}, change_package: {}, interior_color: {}, optional_package: {} });
        },
      });
    });
  };
  labelText = (code: string, label: string) => {
    const { attribute } = this.state;
    if (!label) {
      return '';
    }
    const obj = attribute[code];
    const arr = label.split(',');
    const list: Array<string> = [];
    arr.forEach(e => {
      obj[e] && list.push(obj[e]);
    });

    return list.join();
  };

  getDicLabel = (list: [], val: any) => {
    let tempLabel = '';
    list.some((item: any) => {
      const state = item.value == val;
      if (state) {
        tempLabel = item.label
      }
      return state
    })
    return tempLabel
  }
  onBrandSelect = (value:any) =>{
    this.setState({
      selectBrand: value,
      rightQuery: {},
    },()=>{
      this.searchRef.current.resetFields();
      this.getList({},value),
      this.getSeries(value);
    })
  }
  render() {
    const { rightQuery, isModalOpen, layerInfo, selectList,brandOptions,defaultBrand,selectBrand } = this.state;
    const {
      loading,
      location: { pathname = '/' },
      listData,
    } = this.props;
    const { list, pagination } = listData;
    const options = brandOptions.map((item:any)=>{
      return {
        label: item.brandName,
        value: item.brandCode
      }
    })
    const searchItems = [
      {
        type: 'select',
        title: `车系`,
        key: 'seriesCode',
        selectOptions: selectList,
        keyValue: ['seriesCode', 'seriesName'],
      },
      {
        type: 'input',
        title: `车型`,
        key: 'typeName',
      },
    ];

    const rightColumns = [
      {
        title: `车系`,
        dataIndex: 'seriesName',
      },
      {
        title: `车型`,
        dataIndex: 'typeName',
      },
      {
        title: `车型版本`,
        dataIndex: 'typeCode',
      },
      {
        title: `车身型式`,
        dataIndex: 'bodyName',
      },
      {
        title: `配置级别`,
        dataIndex: 'configLevelName',
      },
      {
        title: `动力装置`,
        dataIndex: 'powerName',
      },
      {
        title: `变数器及驱动形式`,
        dataIndex: 'transName',
      },
      {
        title: `设计与顾客基础`,
        dataIndex: 'dcbaseName',
      },
      {
        title: `年型`,
        dataIndex: 'modelYearName',
      },
      {
        title: `操作`,
        dataIndex: '操作',
        fixed: 'right',
        width: 100,
        render: (text: any, record: any) => {
          const btns = [
            {
              title: '详情',
              key: 'detail',
              auth: 'vehicleModelQuery_detail',
              onConfirm: () => {
                // 获取数据
                this.getAttribute().then(attribute => {
                  // 显示/设置值
                  this.setState({
                    isModalOpen: true,
                    layerInfo: { ...record },
                    attribute,
                  });
                });
              },
            },
          ];
          return <PateoAuthButtons btns={btns} max={2} pathname={pathname} />;
        },
      },
    ];
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => <span>共&nbsp;{!pagination ? 0 : pagination.total}&nbsp;条</span>,
    };
    let numT = 0;
    const rightTable = {
      columns: rightColumns,
      dataSource: [...(list || [])],
      loading,
      rowKey: (record: any) => {
        numT++;
        return numT;
      },
      pagination: paginationProps,
      scroll: { x: 'max-content' },
    };
    const modalFooter = (
      <Space align="center" direction="vertical" style={{ width: '100%' }}>
        <Button type="primary" onClick={this.handleCancel}>
          关闭
        </Button>
      </Space>
    );
    return (
      <div>
        <div  style={{margin: '0px 10px 10px 10px'}}>
          <div style={{display:'inline-block'}}>
          <span>品牌：</span>
            </div>
            <div style={{display:'inline-block'}}>
                 <Select
                    allowClear={false}
                    placeholder="请选择品牌"
                    getPopupContainer={(triggerNode) => triggerNode.parentNode}
                    
                    onChange={this.onBrandSelect}
                    style={{width: '250px'}}
                    key={defaultBrand}
                    defaultValue={defaultBrand}
                    options={options}
                  >
                  </Select>
                  </div>
          </div>
        <Card>
          <PateoSearchForm
            onRef={ref => (this.searchRef = ref)}
            searchItems={searchItems}
            fetchParams={{ type: this.payloadType, url: this.payloadUrl }}
            extraArgs={{ brandId: selectBrand,}}
            saveFormValues={(val: any) =>
              this.setState({ rightQuery: Object.assign(rightQuery, val) })
            }
            handleFormReset={() => this.setState({ rightQuery: {} })}
          />
        </Card>
        <Card className={styles.standardTable}>
          <PateoTable
            extraHandle={true}
            tableProps={rightTable}
            fetchParams={{ type: this.payloadType, url: this.payloadUrl, extraArgs: {brandId: selectBrand} }}
            formValues={rightQuery}
            currentName="pageNo"
          />
        </Card>
        <Modal
          title="车型详情"
          visible={isModalOpen}
          footer={modalFooter}
          width="900px"
          onCancel={this.handleCancel}
        >
          <Descriptions title="基础信息" column={2} style={{ padding: '10px 20px' }}>
            <Descriptions.Item span={1} label="车系">
              {layerInfo.seriesName}
            </Descriptions.Item>
            <Descriptions.Item span={1} label="车系营销名称">
              {layerInfo.saleName}
            </Descriptions.Item>
            <Descriptions.Item span={1} label="车型">
              {layerInfo.typeName}
            </Descriptions.Item>
            <Descriptions.Item span={1} label="车型营销名称">
              {layerInfo.typeSaleName}
            </Descriptions.Item>
          </Descriptions>
          <Descriptions title="装配信息" column={2} style={{ padding: '10px 20px' }}>
            <Descriptions.Item span={1} label="车型版本">
              {layerInfo.typeCode}
            </Descriptions.Item>
            <Descriptions.Item span={1} label="车身型式">
              {layerInfo.bodyName}
            </Descriptions.Item>
            <Descriptions.Item span={1} label="配置级别">
              {layerInfo.configLevelName}
            </Descriptions.Item>
            <Descriptions.Item span={1} label="动力装置">
              {layerInfo.powerName}
            </Descriptions.Item>
            <Descriptions.Item span={1} label="变数器及驱动形式">
              {layerInfo.transName}
            </Descriptions.Item>
            <Descriptions.Item span={1} label="设计与顾客基础">
              {layerInfo.dcbaseName}
            </Descriptions.Item>
            <Descriptions.Item span={1} label="年型">
              {layerInfo.modelYearName}
            </Descriptions.Item>
            <Descriptions.Item span={1} label="车型类别">
              {this.getDicLabel(engineTypeData, layerInfo.engineType)}
            </Descriptions.Item>
            {layerInfo.electricMileage && (<Descriptions.Item span={2} label="纯电续航">
              {layerInfo.electricMileage + 'KM'}
            </Descriptions.Item>
            )}
            <Descriptions.Item span={2} label="tbox类型">
              {layerInfo.tboxTypeName}
            </Descriptions.Item>
            <Descriptions.Item span={2} label="是否一体机">
              {this.getDicLabel(isAllInOneMachineDate, layerInfo.isAllInOneMachine)}
            </Descriptions.Item>
            <Descriptions.Item span={2} label="蓝牙模块类型">
              {this.getDicLabel(bluetoothModuleTypeData, layerInfo.bluetoothModuleType)}
            </Descriptions.Item>
            <Descriptions.Item span={2} label="选装包">
              {this.labelText('optional_package', layerInfo.optionCode)}
            </Descriptions.Item>
            <Descriptions.Item span={2} label="车身颜色">
              {this.labelText('body_color', layerInfo.extcolCode)}
            </Descriptions.Item>
            <Descriptions.Item span={2} label="内饰颜色">
              {this.labelText('interior_color', layerInfo.intcolCode)}
            </Descriptions.Item>
            <Descriptions.Item span={2} label="改装包">
              {this.labelText('change_package', layerInfo.changeCode)}
            </Descriptions.Item>
          </Descriptions>
        </Modal>
      </div>
    );
  }
}

export default connect(mapStateToProps)(index);
